package com.cloudstore.app.a4af6d48384984d889eabd9fd40eb0d15.service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import weaver.file.FileUploadToPath;
import weaver.general.Util;
import weaver.hrm.company.DepartmentComInfo;
import weaver.hrm.company.SubCompanyComInfo;
import weaver.hrm.resource.ResourceComInfo;
import weaver.sms.SMSManager;

import com.alibaba.fastjson.JSON;
import com.cloudstore.api.obj.Auth;
import com.cloudstore.api.util.Util_CheckAuth;
import com.cloudstore.api.util.Util_DateTime;
import com.cloudstore.api.util.Util_ExcelImport;
import com.cloudstore.app.a4af6d48384984d889eabd9fd40eb0d15.dao.Dao_Salary;
import com.cloudstore.app.a4af6d48384984d889eabd9fd40eb0d15.dao.Dao_SalaryFactory;
import com.cloudstore.app.a4af6d48384984d889eabd9fd40eb0d15.entity.Salary;
import com.cloudstore.app.a4af6d48384984d889eabd9fd40eb0d15.entity.SalaryImportMsg;


public class Service_Salary {
	private Dao_Salary d = null; 
	private ResourceComInfo rci = null;
	private DepartmentComInfo dci = null;
	private SubCompanyComInfo scci = null;
	
	public Service_Salary() {
		d = Dao_SalaryFactory.getInstance().getDao("Dao_SalaryImpl");
		try {
			rci = new ResourceComInfo();
			dci = new DepartmentComInfo();
			scci = new SubCompanyComInfo();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public String doSalarySend(HttpServletRequest request,HttpServletResponse response) {
		return d.sendSalaryBySetId(request.getParameter("setId"))?"0":"1";
	}
	
	public String doSalaryDel(HttpServletRequest request,HttpServletResponse response) {
		return d.delSalaryBySetId(request.getParameter("setId"))?"0":"1";
	}
	
	public String doSalaryTypesGet(HttpServletRequest request,HttpServletResponse response) {
		String mainKey = request.getParameter("mainKey");
		String date = request.getParameter("date");
		return JSON.toJSONString(d.getSalaryTypes(mainKey,date));
	}
	
	public List<Salary> getSalaryMsgList(HttpServletRequest request,HttpServletResponse response) {
		String mainKey = request.getParameter("mainKey");
		String date = request.getParameter("date");
		String type = request.getParameter("type");
		String context = request.getParameter("context");
		String userIds = request.getParameter("userIds");
		List<String> contextKeys = new ArrayList<String>();
		if(!"".equals(context)&&null!=context) {
			Matcher m = Pattern.compile("\\[([^\\[\\]]+)\\]").matcher(context); //提取括号中内容

			while(m.find()) {
				contextKeys.add(m.group(1));
			}
		}
		List<Salary> sl = d.getSalaryDataByParams(userIds,mainKey,date,type);
		for(int i=0;i<sl.size();i++) {
			Salary s = sl.get(i);
			String depId = rci.getDepartmentID(s.getUserId());
			String comId = rci.getSubCompanyID(s.getUserId());
			s.setUserName(rci.getResourcename(s.getUserId()));
			s.setDepName(dci.getDepartmentname(depId));
			s.setComName(scci.getSubCompanyname(comId));
			if(null!=s.getHrId()&&!"".equals(s.getHrId())) {
				s.setHrName(rci.getResourcename(s.getHrId()));
				String msgContext = context;
				String nameArr[] = s.getNames().split(",");
				String valueArr[] = s.getValues().split(",");
				for(int j=0;j<contextKeys.size();j++) {
					String contextKey = contextKeys.get(j);
					if("name".equals(contextKey)) {
						msgContext = msgContext.replaceAll("\\["+contextKey+"\\]",s.getUserName());
						//System.out.println("msgContext:"+msgContext+" contextKey:"+contextKey);

					}
					else if("date".equals(contextKey)) {
						msgContext = msgContext.replaceAll("\\["+contextKey+"\\]",date.replace("-","年")+"月");
						//System.out.println("msgContext:"+msgContext+" contextKey:"+contextKey);

					}
					else {
						for(int k=0;k<nameArr.length;k++) {
							if(contextKey.equals(nameArr[k])) {
								msgContext = msgContext.replaceAll("\\["+contextKey+"\\]",valueArr[k]);
								//System.out.println("msgContext:"+msgContext+" contextKey:"+contextKey);

							}
						}
					}
				}
				s.setMsgContext(msgContext);
			}
			sl.set(i,s);
		}
		return sl;
	}
	
	public String doSalaryMsgSend(HttpServletRequest request,HttpServletResponse response) {
		SMSManager sm = new SMSManager();
		List<Salary> sl = this.getSalaryMsgList(request,response);
		for(int i=0;i<sl.size();i++) {
			Salary s = sl.get(i);
			String isMsgSend = "1";
			if(!"-1".equals(s.getIsMsgSend())&&"-1".equals(s.getIsSend())) {
				isMsgSend = sm.sendSMS(s.getMobile(),s.getMsgContext())?"-1":"-3";
				if("-1".equals(isMsgSend)) {
					d.markSalaryMsgSend(s.getId(),isMsgSend);
				}
				if("".equals(s.getMobile())) {
					isMsgSend = "-2"; //手机号未维护

				}
				s.setKey("send"+s.getKey());
			}
			s.setIsMsgSend(isMsgSend);
			sl.set(i,s);
		}
		return JSON.toJSONString(sl);
	}
	
	public String doSalaryMsgDatasGet(HttpServletRequest request,HttpServletResponse response) {
		return JSON.toJSONString(this.getSalaryMsgList(request,response));
	}
	
	public String doSalaryDatasGet(HttpServletRequest request,HttpServletResponse response) {
		return JSON.toJSONString(this.getSalaryDatas(request, response));
	}
	
	public List<Salary> getSalaryDatas(HttpServletRequest request,HttpServletResponse response) {
		Util_CheckAuth uca = new Util_CheckAuth();
		Auth a = null;
		try {
			a = uca.initCloudStore(request,response);
		} catch (IOException e) {
			// TODO Auto-generated catch block

			e.printStackTrace();
		} catch (ParseException e) {
			// TODO Auto-generated catch block

			e.printStackTrace();
		}
		String isHr = request.getParameter("isHr");
		//System.out.println("isHr:"+isHr);

		List<Salary> sl = d.getSalaryListById(a.getUserId(),request.getParameter("date"),"0".equals(isHr));
		for(int i=0;i<sl.size();i++) {
			Salary s = sl.get(i);
			s.setUserName(rci.getResourcename(s.getMainKeyValue()));
			String depId = rci.getDepartmentID(s.getMainKeyValue());
			String comId = rci.getSubCompanyID(s.getMainKeyValue());
			s.setDepName(dci.getDepartmentname(depId));
			s.setComName(scci.getSubCompanyname(comId));
			//s.setComName(scci.getSubcompanyname(comId));

			s.setRealMainKey(d.getRealMainKey(s.getMainKey(),s.getMainKeyValue()));
			sl.set(i,s);
		}
		return sl;
	}
	
	public String doSalaryOutput(HttpServletRequest request,HttpServletResponse response) {
		String setId = request.getParameter("setId");
		List<Salary> sl = this.getSalaryDatas(request, response);
		String fileName = "salary" + Util_DateTime.getNowDateTimeStr() + request.getSession().getId() + ".xls";
		HttpSession session = request.getSession(true);
		File f = new File(session.getServletContext().getRealPath("cloudstore/app/no0000005/file/"));
		if (!f.exists()) {
			f.mkdirs();
		}
		String url = session.getServletContext().getRealPath("cloudstore/app/no0000005/file/" + fileName);
		String realUrl = "/cloudstore/app/no0000005/file/" + fileName;
		//System.out.println("url:"+url);

		//System.out.println("realUrl:"+realUrl);

		//System.out.println("setId:"+setId);

		//if(sl.size()==0) return "1";

		try {
			Util_CheckAuth uca = new Util_CheckAuth();
			Auth a = null;
			try {
				a = uca.initCloudStore(request, response);
			} catch (Exception e) {
				// TODO Auto-generated catch block

				e.printStackTrace();
			}
			HSSFWorkbook workbook = new HSSFWorkbook();
			HSSFSheet sheet = workbook.createSheet();
			workbook.setSheetName(0, "salary", HSSFWorkbook.ENCODING_UTF_16);
			int rowNum = 0;
			int colNum = 0;
			for(int i=0;i<sl.size();i++) {
				Salary ss = sl.get(i);
				if(ss.getSetId().equals(setId)) {
					if(rowNum==0) {
						HSSFRow row = sheet.createRow((short) rowNum++);
						this.setCell(row, colNum++, ss.getMainKey().equals("idCard")?"身份证号码":"工号");
						String sil[] = ss.getNames().split(","); 
						String ssil[] = ss.getValues().split(",");
						for(int j=0;j<sil.length;j++) {
							if(this.isDecimal(ssil[j])) {
								this.setCell(row, colNum++,sil[j]);
							}
							else {
								this.setCell(row, colNum++,sil[j]+"[string]");
							}
						}
					}
					HSSFRow row = sheet.createRow((short) rowNum++);
					colNum = 0;
					this.setCell(row, colNum++,ss.getRealMainKey());
					String ssil[] = ss.getValues().split(",");
					for(int j=0;j<ssil.length;j++) {
						this.setCell(row, colNum++, ssil[j]);
					}
				}
			}
			FileOutputStream fOut = new FileOutputStream(url);
			workbook.write(fOut);
			fOut.flush();
			fOut.close();
			//System.out.println("realUrl1:"+realUrl);

			return realUrl;
		}
		catch(Exception e) {
			e.printStackTrace();
			realUrl = "1";
		}
		//System.out.println("realUrl2:"+realUrl);

		return realUrl;
	}
	
	public static boolean isDecimal(String str) {
		if(str==null || "".equals(str))
			return false;  
		java.util.regex.Pattern pattern = Pattern.compile("[0-9]*(\\.?)[0-9]*");
		return pattern.matcher(str).matches();
	}
	
	public void setCell(HSSFRow r, int n, String value) {
		// TODO Auto-generated method stub

		HSSFCell cell = r.createCell((short) n);
		cell.setCellType(HSSFCell.CELL_TYPE_STRING);
		cell.setEncoding(HSSFCell.ENCODING_UTF_16);
		cell.setCellValue(value);
	}
	
	public String doSalaryImport(HttpServletRequest request,HttpServletResponse response) {
		Util_CheckAuth uca = new Util_CheckAuth();
		Auth a = null;
		try {
			a = uca.initCloudStore(request,response);
		} catch (IOException e) {
			// TODO Auto-generated catch block

			e.printStackTrace();
		} catch (ParseException e) {
			// TODO Auto-generated catch block

			e.printStackTrace();
		}
		FileUploadToPath fu = new FileUploadToPath(request);    //非压缩上传

		String filePath = fu.uploadFiles("excelFile");
		String date = Util.null2String(fu.getParameter("date"));
		String type = Util.null2String(fu.getParameter("type"));
		try {
			type = new String(type.getBytes("ISO-8859-1"),"utf-8");
		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block

			e1.printStackTrace();
		}
		/*

		try {

			byte[] b = fu.getParameter("type").getBytes();

			type = new String(b,"GBK");

		} catch (UnsupportedEncodingException e1) {

			// TODO Auto-generated catch block

			e1.printStackTrace();

		}*/
		String mainKey = Util.null2String(fu.getParameter("mainKey"));
		//System.out.println("date:"+date);

		//System.out.println("type:"+type);

		//System.out.println(filePath);

		List<SalaryImportMsg> msg = new ArrayList<SalaryImportMsg>();
		HSSFWorkbook book = null;
		boolean canImport = true;
		try {
			//初始化

			book = Util_ExcelImport.getExcelWorkbook(filePath);
			HSSFSheet sheet = Util_ExcelImport.getSheetByNum(book,1);
			HSSFRow row = null;
			//int rowNum = 0;

			//校验第1行表头

			row = sheet.getRow(0);
			StringBuilder fields = new StringBuilder();
			StringBuilder fieldTypes = new StringBuilder();
			StringBuilder names = new StringBuilder();
			for(int i=1;i<row.getLastCellNum();i++) {
				String fieldLabel = Util_ExcelImport.getCellValue(row.getCell((short)i));
				String fieldLabelType = "[double]";
				String regex = "\\[([^\\[\\]]+)\\]";
		        Pattern p = Pattern.compile(regex);
		        Matcher m = p.matcher(fieldLabel);
		        while(m.find()) {
		            //System.out.println(m.group());

		            fieldLabelType = m.group();
		        }
		        fields.append(fieldLabelType);
		        fieldTypes.append(fieldLabelType);
		        
		        if("[string]".equals(fieldLabelType)) {
		        	names.append(fieldLabel.substring(0,fieldLabel.indexOf("[string]")));
		        }
		        else {
		        	names.append(fieldLabel);
		        }
		        if(i!=row.getLastCellNum()-1) {
		        	fields.append(",");
		        	fieldTypes.append(",");
		        	names.append(",");
		        }
		        /*

		         * 不需要添加动态列

		        if(!d.addFieldColumn("v"+i)) {

		        	canImport = false;

		        	SalaryImportMsg sim = new SalaryImportMsg();

					sim.setType("error");

					sim.setValue("表头初始化异常，请联系系统管理员！");

					msg.add(sim);

		        }

		        */
			}
			Salary s = new Salary();
			s.setMainKey(mainKey);
			s.setType(type);
			s.setDate(date);
			s.setFields(fields.toString());
			s.setFieldTypes(fieldTypes.toString());
			s.setNames(names.toString());
			s.setHrId(Integer.toString(a.getUserId()));
			int id = d.findSalarySet(s);
			if(id!=0&&canImport)
				canImport = d.editSalarySet(s);
			else if(canImport) {
				id = d.addSalarySet(s);
				if(id==0) {
					canImport = false;
				}
			}
			if(!canImport) {
				SalaryImportMsg sim = new SalaryImportMsg();
				sim.setType("error");
				sim.setValue("表头初始化异常，请联系系统管理员！");
				msg.add(sim);
			}
			else {
				s.setId(Integer.toString(id));
				//检验内容

				String[] fieldArr = fields.toString().split(",");
				String[] fieldTypeArr = fieldTypes.toString().split(",");
				//String[] nameArr = names.toString().split(",");

				//String[] valueArr = new String[fieldArr.length];

				//System.out.println("row:"+sheet.getLastRowNum()+" id:"+id);

				//StringBuilder names1 = new StringBuilder();

				for(int i=1;i<=sheet.getLastRowNum();i++) {
					row = sheet.getRow(i);
					String mk = Util_ExcelImport.getCellValue(row.getCell((short)0));
					if(!"".equals(mk)) {
						String userId = Integer.toString(d.findUserId(mainKey,mk));
						if("0".equals(userId)) {
							SalaryImportMsg sim = new SalaryImportMsg();
							sim.setType("warn");
							sim.setValue("第"+i+"行找不到用户，相关主键["+mk+"]！");
							msg.add(sim);
						}
						else {
							s.setMainKeyValue(mk);
							s.setUserId(userId);
							StringBuilder values = new StringBuilder();
							for(int j=0;j<fieldArr.length;j++) {
								String value = "";
								if("[string]".equals(fieldTypeArr[j])) {
									value = Util_ExcelImport.getCellValue(row.getCell((short)(j+1)));
								}
								else if("[double]".equals(fieldTypeArr[j])) {
									value = Util_ExcelImport.getCellValue2(row.getCell((short)(j+1)));
								}
								values.append(value);
								if(j!=fieldArr.length-1) {
									values.append(",");
								}
							}
							s.setValues(values.toString());
							if(!d.findSalary(s)) {
								if(!d.addSalary(s)) {
									SalaryImportMsg sim = new SalaryImportMsg();
									sim.setType("warn");
									sim.setValue("第"+i+"行数据写入异常，相关主键["+mk+"]，请联系管理员！");
									msg.add(sim);
								}
							}
							else {
								if(!d.editSalary(s)) {
									SalaryImportMsg sim = new SalaryImportMsg();
									sim.setType("warn");
									sim.setValue("第"+i+"行数据写入异常，相关主键["+mk+"]，请联系管理员！");
									msg.add(sim);
								}
								else {
									SalaryImportMsg sim = new SalaryImportMsg();
									sim.setType("warn");
									sim.setValue("第"+i+"行数据被覆盖，相关主键["+mk+"]！");
									msg.add(sim);
								}
							}
						}
					}
				}
			}
		}catch(Exception e) {
			e.printStackTrace();
			SalaryImportMsg sim = new SalaryImportMsg();
			sim.setType("error");
			sim.setValue("导入模板格式有误，请检查或者联系管理员！");
			msg.add(sim);
		}
		if(msg.size()==0) {
			SalaryImportMsg sim = new SalaryImportMsg();
			sim.setType("success");
			sim.setValue("导入成功！");
			msg.add(sim);
		}
		else if(canImport) {
			SalaryImportMsg sim = new SalaryImportMsg();
			sim.setType("warn");
			sim.setValue("导入成功，但有异常项！");
			msg.add(sim);
		}
		return JSON.toJSONString(msg);
	}
}
